# -*- coding:utf-8 -*-

import math, traceback
from server.util import errors, stringUtil
from server.action import breg, besd, bmof, bmon, lreg, lron, lrof, lcdo, lcdc, lckw, lcdd, extr, kill, bell


class serviceHandler(object):  # Service for fan

    def __init__(self, re, db, tin):  # reids, mysql, socket容器
        self.actionsFromBaseStation = {
            # "blgd": blgd.blgd(db),
            # "bcof": bcof.bcof(db),
            # "bcsd": bcsd.bcsd(db),
            # "bpcs": bpcs.bpcs(db),
            # "blrg": blrg.blrg(db),
            # "bldq": bldq.bldq(db),
            "breg": breg.breg(db, re),  # 建立连接
            "besd": besd.besd(db, re),  # 温、湿、光
            "lreg": lreg.lreg(db, re),  # 灯端从属关系初始化
            "lron": lron.lron(db, re),  # 更新当前灯端状态（开）
            "lrof": lrof.lrof(db, re),  # 更新当前灯端状态（关）
            "lcdo": lcdo.lcdo(db, re),  # 开盖
            "lcdc": lcdc.lcdc(db, re),  # 关盖
            "lckw": lckw.lckw(db, re), # 功率
            "lcdd": lcdd.lcdd(db, re), # 断电
            "extr": extr.extr(db, re)  # 将单条命令发给基站
        }
        self.actionsFromFrokProcess = {
            # "seon": seon.seon(db, re),  # open all street
            # "seof": seof.seof(db, re),  # close all street
            # "bmon": bmon.bmon(db),  # open lamp all
            # "bmof": bmof.bmof(db),  # close lamp all
            # "lnon": lnon.lnon(db, re),  # open one
            # "lnof": lnof.lnof(db, re),  # close one
            "kill": kill.kill(db, re),  # 断开连接
            "bell": bell.bell(db, re)  # 通知基站获取数据
        }
        self.tin = tin
        self.re, self.db = re, db

    def data_handler(self, data, d, socket):
        fixingId, command = data[0], data[1]
        try:
            # method
            if command in self.actionsFromBaseStation.keys():  # 来自基站的命令
                self.socketHandler(fixingId, socket)

                self.actionsFromBaseStation[command].action(data, d)
            elif command in self.actionsFromFrokProcess.keys():  # 来自守护进程的任务命令
                if self.tin.get(fixingId) is None:
                    raise errors.Illegal("error[1004]: 无法建立与基站的连接: ID[%s]" % fixingId)

                self.actionsFromFrokProcess[command].action(data, d)
            else:
                raise errors.Illegal("error[1003]: 未知的命令: ID[%s] Command[%s]" %(fixingId, command))

        except Exception, e:
            mes = traceback.format_exc()
            print mes
            d.errback(e)

    def socketHandler(self, baId, socket):
        isHave = self.tin.get(baId)

        if isHave is None:
            self.tin.save(baId, socket)  # 保存socket
        else:
            if isHave != socket:
                self.tin.save(baId, socket)  # 更新socket
